package com.sihuatech.coreagent.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.sihuatech.coreagent.core.communication.entity.StmView;
import com.sihuatech.coreagent.core.communication.entity.StmViewHistory;
import com.sihuatech.coreagent.mapper.StmViewHistoryMapper;
import com.sihuatech.coreagent.mapper.StmViewMapper;



@Component
public class TimedTaskController {

	private static final Logger logger = LoggerFactory.getLogger(TimedTaskController.class);

	@Value("${ftp.byTimeFile.upload.path}")
	private String byTimeFilePath;

	@Value("${ftp.upFile.upload.blankTime}")
	private Integer blankTime;

	@Value("${ftp.byTimeFile.upload.switch}")
	private boolean fileGenerateSwitch;

	@Autowired
	private StmViewMapper stmViewMapper;

	@Autowired
	private StmViewHistoryMapper stmViewHistoryMapper;

	@Scheduled(cron = "${ftp.byTimeFile.upload.time}")
	public void uploadByTimeFile() throws Exception {
		if (!fileGenerateSwitch){
			logger.info("生成话单文件开关未开启！");
			return;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
		Date endTime = new Date();
		logger.info("按次话单文件生成本地文件定时任务开启:" + sdf.format(endTime));
		Calendar startTime = Calendar.getInstance();
		//校验配置的时间间隔
		int times = 24*60 / blankTime;
		if(times + 1 > 999) {
			logger.info("请校验配置项:[" + blankTime + "]应不小于1");
			return;
		}
		String num = String.format("%03d",
				(startTime.get(Calendar.HOUR_OF_DAY) * 60 + startTime.get(Calendar.MINUTE)) / blankTime);// TODO 解出文件序号
		startTime.add(Calendar.MINUTE, 0 - blankTime);
		Date starttime = startTime.getTime();
		//sql查询时间在starttime和当前时间之间的话单数据;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<StmView> stmViewList = stmViewMapper.selectBetweenTime(format.format(starttime), format.format(endTime));
		File file = new File(byTimeFilePath);// 先生成配置项的文件夹
		if (!file.exists()) {
			file.mkdirs();
		}

		if (stmViewList == null || stmViewList.size() == 0) {
			logger.info("当前数据库无符合条件的STM话单文件需要上传");
		} else {
			//TODO 方便测试 后续删除
			File fileUpByTime = new File(byTimeFilePath + "/" + "STM" + ymd.format(endTime) + num + ".013" + "TEMP");// 下发流媒体结算文件名
			if (!fileUpByTime.exists()) {
				logger.info("---------创建文件！-------------"+fileUpByTime.getName());
				fileUpByTime.createNewFile();
			}
			StringBuffer buffer = new StringBuffer();// 存放话单信息
			String headDesc = "";//存放头记录信息
			String tailDesc = "";//存放尾记录信息
			int fee = 0;//存放信息费

			String provinceCodes = "";
			List<StmView> stmViewForHistorys = new ArrayList<>(stmViewList.size());
			for (StmView stmView : stmViewList) {
				// 文件序号位数 时间需要不需要修改
				if (!StringUtils.equals(stmView.getFileNum(), num + "_")) {
					//文件序号和定时任务解析的不一致时 需要修改
					stmView.setFileNum(num);
					stmView.setHeadDesc(new StringBuffer(stmView.getHeadDesc()).replace(40, 44, num + "_").toString());
					stmView.setTailDesc(new StringBuffer(stmView.getTailDesc()).replace(30, 34, num + "_").toString());
				}
				logger.info(stmView.getTailDesc());
				if (StringUtils.isBlank(headDesc)) {
					headDesc = stmView.getHeadDesc().replace("_", " ");
					StringBuilder headStr = new StringBuilder(headDesc);
					headStr.replace(7,10,"013");
					headDesc = headStr.toString();
				}
				if (StringUtils.isBlank(tailDesc)) {
					tailDesc = stmView.getTailDesc().replace("_", " ");
					StringBuilder tailStr = new StringBuilder(tailDesc);
					tailStr.replace(27,30,"013");
					tailDesc = tailStr.toString();
				}
				buffer.append(StringUtils.replace(stmView.getMiddleDesc(), "_", " ").substring(0,292) + "\r\n");
				//信息费合计
				StringBuffer midd = new StringBuffer(stmView.getMiddleDesc());
				fee += Integer.valueOf(midd.substring(138,146));

				stmView.setHeadDesc(headDesc.replace(" ","_"));
				StringBuffer bfTail = new StringBuffer(tailDesc);
				bfTail.replace(117, 127, "0000000000");
				stmView.setTailDesc(String.valueOf(bfTail).replace(" ","_"));
				StringBuffer bfMidd = new StringBuffer(stmView.getMiddleDesc());
				bfMidd.replace(292,293,"_");
				stmView.setMiddleDesc(String.valueOf(bfMidd));
				stmViewForHistorys.add(stmView);
			}
			StringBuffer str = new StringBuffer(String.valueOf(fee));
			StringBuffer numStr = new StringBuffer(String.valueOf(stmViewList.size()));
			if(StringUtils.isNotBlank(tailDesc)) {
				boolean flag = true;
				while (flag){
					if (str.length() < 10){
						str.insert(0,"0");
					} else if (str.length() == 10){
						flag = false;
					}
				}
				boolean numFlag = true;
				while (numFlag){
					if (numStr.length() < 9){
						numStr.insert(0,"0");
					} else if(numStr.length() == 9){
						numFlag = false;
					}
				}
				tailDesc = new StringBuffer(tailDesc).replace(58,67,numStr.toString()).replace(107,117,str.toString()).replace(117, 127, "0000000000").replace(44, 58, sdf.format(endTime)).substring(0,292).toString() + "\r\n";
			}
			if(StringUtils.isNotBlank(headDesc))
				headDesc = new StringBuffer(headDesc).replace(64, 78, sdf.format(endTime)).substring(0,292).toString();

			//TODO 读入失败和读入成功的处理 关于历史表
			//将组织的文件内容读入文件 begin
			FileWriter fw;
			try {
				fw = new FileWriter(fileUpByTime, true);
				fw.write(headDesc + "\r\n" + buffer.toString() + tailDesc);// 写入本地文件中
				fw.flush();
				fw.close();
				boolean renameTo = fileUpByTime.renameTo(new File(byTimeFilePath + "/" + "STM" + ymd.format(endTime) + num + ".013"));
				if(renameTo) {
					//stmViewForHistorys
					for(StmView stmView : stmViewForHistorys) {
						StmViewHistory stmViewHistory = new StmViewHistory();
						try {
							BeanUtils.copyProperties(stmViewHistory, stmView);
							stmViewHistory.setId(null);
							if(stmViewHistoryMapper.insert(stmViewHistory) == 1)
								stmViewMapper.deleteById(stmView.getId());
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			} catch (IOException e) {
				logger.error("生成数据文件异常，" + e);
			}
			//end
		}
	}

}
